package com.mud.ultimate.tasks;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.mud.ultimate.data.GameRecord;

public class AsyncTaskDownloadHighScores extends AsyncTask<String, Void, List<GameRecord>> {

	public interface DownloadHighScoresCompleteListener {
		   public void onTaskComplete(List<GameRecord> aResult);
		   public void onError(String aError);
	}
	
	private Context context = null;
	private ProgressDialog progressDialog = null;
	private DownloadHighScoresCompleteListener listener;
	private String error = null;


	public AsyncTaskDownloadHighScores(Context context, DownloadHighScoresCompleteListener aListener) {
	    this.context = context; 
	 
	    listener = aListener;
		
	}
	
	@Override
	protected void onPreExecute() {
		progressDialog = new ProgressDialog(this.context);
	    progressDialog.setMessage("Downloading high scores...");
	    progressDialog.show();
	}
	
	@Override
	protected List<GameRecord> doInBackground(String... params) {
		
		BufferedReader reader = null;
		String result = "";
		
		List<GameRecord> recordList = new ArrayList<GameRecord>();
		
		try {
			URL url = new URL("http://meadmin-mudstudio.rhcloud.com/rest/Score/toplist");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			
			String line = "";
			while ((line = reader.readLine()) != null) {
				result += line;
			}
			
			
			JSONArray recordListJSON = new JSONArray(result);
			for(int i=0; i<recordListJSON.length(); i++)
			{
				JSONObject gameRecordJSON = recordListJSON.getJSONObject(i);
				GameRecord gameRecord = new GameRecord(URLDecoder.decode(gameRecordJSON.getString("name")),
													   gameRecordJSON.getInt("score"),
													   new Date(gameRecordJSON.getLong("date")));
				recordList.add(gameRecord);
					
			}
			
			
		} catch (IOException e) {
			error = e.getMessage();
			e.printStackTrace();
		} catch (JSONException e) {
			error = e.getMessage();
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					error = e.getMessage();
					e.printStackTrace();
				}
			}
		}
	
		
		return recordList;
	}
	
	@Override
	protected void onPostExecute(List<GameRecord> result) {
	    progressDialog.dismiss();
	    if (error != null) {
	    	listener.onError(error);
	    }
	    else {
	    	listener.onTaskComplete(result);
	    }
	}
}